package com.boboPlanet.service.impl;

import com.boboPlanet.comm.enums.GatewayConstance;
import com.boboPlanet.comm.result.ResponseResult;
import com.boboPlanet.enums.GatewayErrorEnum;
import com.boboPlanet.service.PageExceptionHandler;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import reactor.core.publisher.Mono;
import reactor.netty.ByteBufMono;

/**
 * @Description: TODO
 * @Author: mis_wu
 * @Date: 2023/2/13
 **/
@Service
@Slf4j
public class PageExceptionHandlerImpl implements PageExceptionHandler{

    private static final Boolean IS_ERROR = Boolean.FALSE;

    @Override
    public Mono<Void> pageExceptionHandler( ServerHttpResponse response, HttpStatus status,String ...errorMsg) {
        ResponseResult<Boolean> result;
        ObjectMapper objectMapper = new ObjectMapper();
        String resultStr;
        try {
            result = ResponseResult.error(null,IS_ERROR,errorMsg);
            resultStr = objectMapper.writeValueAsString(result);
        } catch (JsonProcessingException e) {
            log.error(e.getMessage(),e);
            throw new RuntimeException(GatewayErrorEnum.AUTHORIZATION_TOKEN.getMsg());
        }
        //返回给页面 token is null
        DataBuffer dataBuffer = response.bufferFactory()
                .allocateBuffer().write(resultStr.getBytes());
        response.setStatusCode(status != null? status : HttpStatus.OK);

        //基于流形式
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        return response.writeAndFlushWith(Mono.just(ByteBufMono.just(dataBuffer)));
    }

    @Override
    public void requestLogPrint(String reqAddr,String reqMethod, MultiValueMap<String, String> getParams, String postParam) {
        if (GatewayConstance.GET_REQUEST.equals(reqMethod)){
            log.info("网关【{}】请求接口：{}  ,参数：{}",reqMethod,reqAddr,getParams);
        }
        if (GatewayConstance.POST_REQUEST.equals(reqMethod)){
            log.info("网关【{}】请求接口：{}  ,参数：{}",reqMethod,reqAddr,postParam);
        }
        if (GatewayConstance.PUT_REQUEST.equals(reqMethod)){
            log.info("网关【{}】请求接口：{}  ,参数：{}",reqMethod,reqAddr,postParam);
        }
    }
}
